package com.kotlin.heimaplayer.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.heimaplayer.widget.LoadMoreView

abstract class BaseListAdapter<ITEMBEAN,ITEMVIEW:View> : RecyclerView.Adapter<BaseListAdapter.BaseListHolder>() {

    private var list = ArrayList<ITEMBEAN>()

    /**
     * 更新数据
     */
    fun updateList(list:List<ITEMBEAN>?){
        list?.let {
            this.list.clear()
            this.list.addAll(list)
            notifyDataSetChanged()
        }

    }

    /**
     * 加载更多
     */
    fun loadMore(list:List<ITEMBEAN>?){
        list?.let {
            this.list.addAll(list)
            notifyDataSetChanged()
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseListHolder {
        if(viewType == 1){
            // 最后一条
            return BaseListHolder(LoadMoreView(parent.context))

        }else{
            return BaseListHolder(getItemView(parent.context))

        }
    }

    abstract fun getItemView(context: Context?): ITEMVIEW

    override fun getItemViewType(position: Int): Int {
        if(position == list.size){
            // 最后一条
            return 1
        }else{
            return 0
        }
    }

    override fun getItemCount(): Int {
        return list.size+1
    }

    override fun onBindViewHolder(holder: BaseListHolder, position: Int) {
        if(position == list.size){
            return
        }
        // 条目数据
        val data = list.get(position)
        // 条目view
        val itemView = holder.itemView as ITEMVIEW
        // 条目刷新
        refreshView(itemView,data)

        // 点击事件
        itemView.setOnClickListener {
            // 条目点击事件
//            listener?.let {
//                it(data)
//            }
            listener?.invoke(data)

        }

    }

    // 定义了一个函数类型变量
    var listener:((itemBean:ITEMBEAN)->Unit)? = null

    fun setMyListener(listener:(itemBean:ITEMBEAN)->Unit){
        this.listener = listener
    }

    // 刷新条目
    abstract fun refreshView(itemView: ITEMVIEW, data: ITEMBEAN?)


    class BaseListHolder(itemView:View):RecyclerView.ViewHolder(itemView){

    }
}